#define _CRT_SECURE_NO_WARNINGS  1

#include"list.h"

Lnode* Buynewnode(datatype x)
{
	Lnode* newnode = (Lnode*)malloc(sizeof(Lnode));
	newnode->data = x;
	newnode->next = NULL;
	newnode->pre = NULL;


	return newnode;
}


Lnode* Initlist()
{

	Lnode* phead = (Lnode*)malloc(sizeof(Lnode));

	phead->next = phead;
	phead->pre = phead;

	return phead;
}

void ListPushFront(Lnode* phead, datatype x)
{
	assert(phead);

	Lnode* newnode = Buynewnode(x);
	Lnode* first = phead->next;
	phead->next = newnode;
	newnode->pre = phead;

	newnode->next = first;
	first->pre = newnode;
}

void ListPrint(Lnode* phead)
{
	assert(phead);

	Lnode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(Lnode* phead,datatype x)
{
	assert(phead);

	Lnode* newnode = Buynewnode(x);
	Lnode* tail = phead->pre;
	

	newnode->next = phead;
	newnode->pre = tail;
	phead->pre = newnode;
    tail->next = newnode;
	
}

bool ListEmpty(Lnode* phead)
{
	assert(phead);
	if (phead->next == phead)
		return false;
	else
		return true;
}

void ListPopBack(Lnode* phead)
{
	assert(phead);
	assert(ListEmpty(phead));

	Lnode* tail = phead->pre;

	phead->pre = tail->pre;
	tail->pre->next = phead;

	free(tail);
	tail = NULL;
}


void ListPopFront(Lnode* phead)
{
	assert(phead);
	assert(ListEmpty(phead));

	Lnode* start = phead->next;

	phead->next = start->next;
	start->next->pre = phead;

	free(start);
	start == NULL;
}

Lnode* ListFind(Lnode* phead,datatype x)
{
	Lnode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		
		cur = cur->next;

	}
	return NULL;
}

void ListInsert(Lnode* pos, datatype x)
{
	Lnode* newnode = Buynewnode(x);

	Lnode* prev = pos->pre;
	newnode->next = pos;
	newnode->pre = prev;
	prev->next = newnode;
	pos->pre = newnode;

}


void ListPop(Lnode* pos)
{
	assert(pos);

	Lnode* prev = pos->pre;
	Lnode* next = pos->next;
	prev->next = next;
	next->pre = prev;

	free(pos);
	pos == NULL;
}

void ListDestroy(Lnode* phead)
{
	Lnode* cur = phead->next;
	while (cur != phead)
	{
		Lnode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(phead);

}